package com.llbnk.controller;

import com.llbnk.error.BusinessException;
import com.llbnk.error.EmBusinessError;
import com.llbnk.response.CommonReturnType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shkstart
 * @create 2022-08-20 10:28
 */
@Slf4j
@RestController
public class BaseController {

    //请求头Content-Type  application/x-www-form-urlencoded  最常见的 POST 提交数据的方式
    //浏览器的原生 表单，如果不设置 enctype 属性
    // 那么最终就会以 application/x-www-form-urlencoded 方式提交数据。
    //https://zhuanlan.zhihu.com/p/347547166
    public static final String CONTENT_TYPE_FORMED="application/x-www-form-urlencoded";

    //controller的业务异常是业务处理的最后一道关口
    //因为controller层处理掉了，那么返回给前端就不是errpage了
    //所以需要定义exceptionhandler解决未被controller层吸收的exception
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public Object handlerException(HttpServletRequest request, Exception ex){
        CommonReturnType commonReturnType = new CommonReturnType();
        log.info("错误信息： msgbody[" + ex+"]");
        commonReturnType.setStatus("fail");
        Map<String,Object> responseData = new HashMap<>();
        if(ex instanceof BusinessException){
            BusinessException businessException = (BusinessException)ex;
            //如果像下面这个设计直接data用exception的包装返回是不行的，应该返回我们自己定义的exception
            //里面应该仅仅有errcode 和 errMsg 这两个值
            //commonReturnType.setData(ex);
            responseData.put("errorCode",businessException.getErrCode());
            responseData.put("errorMsg",businessException.getErrMsg());
        }else{
            responseData.put("errorCode", EmBusinessError.UNKNOW_ERROR.getErrCode());
            responseData.put("errorMsg",EmBusinessError.UNKNOW_ERROR.getErrMsg());
        }
        commonReturnType.setData(responseData);
        return commonReturnType;
    }
}
